package com.apress.messaging.web.socket;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Component
public class MyHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
	    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
	        if (request instanceof ServletServerHttpRequest) {
	            String  query   =   ((ServletServerHttpRequest) request).getServletRequest().getParameter("uid");
	            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
	            servletRequest.setAttribute("uid", query);
	            String uid = (String)servletRequest.getAttribute("uid");
	            if(uid!=null){
	                attributes.put("uid", uid);
	            }else{
	                return false;
	            }
	        }
	        return true;
	    }

	    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
	    System.out.println("after hand");
	    
	    }
}
